package com.hliushi.demo.config;

import com.iflytek.bp.common.config.liquibase.AsyncSpringLiquibase;
import com.iflytek.bp.common.repository.DefaultBpJpaRepository;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author: yxzhang23
 * @time: 2021/3/23
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.hliushi.demo.repository",
        repositoryBaseClass = DefaultBpJpaRepository.class)
@EnableConfigurationProperties(LiquibaseProperties.class)
public class DataBaseConfiguration {

    private final Environment env;

    public DataBaseConfiguration(Environment env) {
        this.env = env;
    }

    @Bean
    public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor, DataSource dataSource,
                                     LiquibaseProperties liquibaseProperties) {
        SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env);
        liquibase.setDataSource(dataSource);
        liquibase.setChangeLog(liquibaseProperties.getChangeLog());
        liquibase.setContexts(liquibaseProperties.getContexts());
        liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
        liquibase.setDropFirst(liquibaseProperties.isDropFirst());
        liquibase.setShouldRun(liquibaseProperties.isEnabled());
        liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
        return liquibase;
    }

}

